package com.solotiger.geographic.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.solotiger.geographic.R;
import com.solotiger.geographic.biz.BaseSubscriber;
import com.solotiger.geographic.biz.api.NetWorkApi;
import com.solotiger.geographic.biz.model.Picture;
import com.solotiger.geographic.biz.model.PictureResult;
import com.solotiger.geographic.common.AppEngine;
import com.solotiger.geographic.db.DatabaseManger;
import com.solotiger.geographic.ui.adapter.PictureAdapter;
import com.solotiger.geographic.ui.base.BaseActivity;
import com.solotiger.geographic.util.FileUtil;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;

/**
 * 图片
 */
public class PictureActivity extends BaseActivity {

    public final static String A_ID = "A_ID";
    public final static String A_TITLE = "A_TITLE";

    private String albumId;

    @BindView(R.id.viewpager)
    ViewPager mViewPager;

    @BindView(R.id.title)
    TextView mTvTitle;

    @BindView(R.id.page)
    TextView mTvPage;

    @BindView(R.id.tv_collect)
    TextView mTvCollect;

    @BindView(R.id.iv_collect)
    ImageView mIvCollect;

    @BindView(R.id.tv_download)
    TextView mTvDownload;

    @BindView(R.id.iv_download)
    ImageView mIvDownload;

    @BindView(R.id.content)
    TextView mTvContent;

    private PictureAdapter mAdapter;

    private int currentIndex;

    private Picture currentItem;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        init();
    }

    /**
     * 初始化
     */
    private void init() {
        albumId = getIntent().getStringExtra(PictureActivity.A_ID);
        String title = getIntent().getStringExtra(PictureActivity.A_TITLE);

        setTitle(title);
        getToolbar().setNavigationIcon(R.drawable.back);
        setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        loadData();
    }

    /**
     * 初始化viewPaper
     */
    private void initViewPager(List<Picture> pictureList) {
        currentIndex = 0;
        mAdapter = new PictureAdapter(mContext, pictureList);
        mViewPager.setAdapter(mAdapter);
        ViewPager.OnPageChangeListener pageChangeListener = new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                Picture picture = mAdapter.getItem(position);
                if (picture == null) {
                    return;
                }
                currentIndex = position;
                currentItem = picture;
                mTvTitle.setText(picture.getTitle());
                mTvPage.setText((position + 1) + "/" + mAdapter.getCount());
                mTvContent.setText(picture.getContent());

                if (DatabaseManger.ME.isCollect(picture)) {
                    mTvCollect.setText(R.string.txt_collected);
                    mIvCollect.setImageResource(R.drawable.collected);
                } else {
                    mTvCollect.setText(R.string.txt_collect);
                    mIvCollect.setImageResource(R.drawable.collect);
                }
                String fileName = FileUtil.getFileName(picture.getUrl(), true);
                if (AppEngine.ME.getDownloadList().contains(fileName)) {
                    mTvDownload.setText(R.string.txt_downloaded);
                    mIvDownload.setImageResource(R.drawable.downloaded);
                } else {
                    mTvDownload.setText(R.string.txt_download);
                    mIvDownload.setImageResource(R.drawable.download);
                }
            }
        };

        mViewPager.addOnPageChangeListener(pageChangeListener);
//        mViewPager.setCurrentItem(0);
        pageChangeListener.onPageSelected(currentIndex);
    }

    /**
     * 加载数据
     */
    private void loadData() {
        NetWorkApi.getPictureByAlbumId(albumId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<PictureResult>() {
                    @Override
                    public void onNext(PictureResult pictureResult) {
                        if (pictureResult != null) {
                            initViewPager(pictureResult.getPicture());
                        } else {
                            showMessage(R.string.txt_load_error);
                        }
                    }

                    @Override
                    protected void _onError(Throwable e) {
                        showMessage(R.string.txt_load_error);
                    }
                });
    }


    @OnClick({R.id.layout_shared, R.id.layout_collect, R.id.layout_download})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.layout_shared:
                Intent intent = new Intent(Intent.ACTION_SEND);
                intent.setType("image/*");
                intent.putExtra(Intent.EXTRA_SUBJECT, "Share");
                intent.putExtra(Intent.EXTRA_TEXT, currentItem.getUrl());
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(Intent.createChooser(intent, getTitle()));
                break;
            case R.id.layout_collect:
                collect();
                break;
            case R.id.layout_download:
                download(currentItem.getUrl());
                break;
        }
    }

    private void download(final String url) {
        NetWorkApi.downloadPic(url)
                .subscribeOn(Schedulers.io())
                .map(new Function<ResponseBody, Boolean>() {

                    @Override
                    public Boolean apply(ResponseBody responseBody) {
                        String fileName = FileUtil.getFileName(url, true);
                        boolean b = FileUtil.saveToDisk(FileUtil.getFileName(url, true), responseBody);
                        if (b) {
                            AppEngine.ME.getDownloadList().add(fileName);
                        }
                        return b;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<Boolean>() {
                    @Override
                    public void onNext(Boolean b) {
                        if (b) {
                            mTvDownload.setText(R.string.txt_downloaded);
                            mIvDownload.setImageResource(R.drawable.downloaded);
                            showMessage("下载成功!");
                        } else {
                            showMessage(R.string.txt_load_error);
                        }
                    }

                    @Override
                    protected void _onError(Throwable e) {
                        showMessage(R.string.txt_load_error);
                    }
                });
    }

    /**
     * 收藏和取消收藏操作
     */
    private void collect() {
        if (DatabaseManger.ME.isCollect(currentItem)) {
            DatabaseManger.ME.deleteItem(currentItem.getId());
            showMessage("已取消收藏!");
            mTvCollect.setText(R.string.txt_collect);
            mIvCollect.setImageResource(R.drawable.collect);
        } else {
            mTvCollect.setText(R.string.txt_collected);
            mIvCollect.setImageResource(R.drawable.collected);
            DatabaseManger.ME.saveCollect(currentItem);
            showMessage("收藏成功!");
        }

    }


    @Override
    protected int getLayoutResId() {
        return R.layout.activity_picture;
    }
}
